#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2019/2/23 16:54
@desc
"""
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
# Project: spd-sxmcc
"""
@author: lyndon
@time Created on 2019/2/23 16:54
@desc
"""

import MySQLdb
from DBUtils.PooledDB import PooledDB
from bratislava.db import getconninfo2

class OPMysql(object):

    __pool = None

    def __init__(self, db_url):
        # 构造函数，创建数据库连接、游标
        self.db_info = getconninfo2(db_url)
        self.coon = self.get_conn()


    # 数据库连接池连接
    def get_conn(self):
        if OPMysql.__pool is None:
            __pool = PooledDB(creator=MySQLdb, mincached=5, maxcached=20, host=self.db_info['host'],
                              user=self.db_info['username'], passwd=self.db_info['password'], db=self.db_info['database'],
                              port=self.db_info['port'], charset=self.db_info['charset'])
            print(__pool)
        return __pool.connection()

    # 插入\更新\删除sql
    def op_insert(self, sql):
        cur = self.coon.cursor()
        insert_num = cur.execute(sql)
        self.coon.commit()
        cur.close()
        return insert_num

    # 查询一行
    def op_select_one(self, sql):
        cur = self.coon.cursor()
        cur.execute(sql)  # 执行sql
        select_res = cur.fetchone()  # 返回结果为字典
        cur.close()
        return select_res

    # 查询多行
    def op_select_all(self, sql):
        cur = self.coon.cursor()
        cur.execute(sql)  # 执行sql
        select_res = cur.fetchall()  # 返回结果为字典
        cur.close()
        return select_res

    #释放资源
    def dispose(self):
        self.coon.close()

